<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.TemplateName" placeholder="输入名称查询" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        查询
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        添加
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column label="Id" prop="id" sortable="custom" align="center" width="80" :class-name="getSortClass('id')">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="创建时间" align="center">
        <template slot-scope="{row}">
          <span>{{ row.timestamp | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column> -->
      <el-table-column label="模板名称" align="center">
        <template slot-scope="{row}">
          <span>{{ row.templateName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="包括模块" align="center">
        <template slot-scope="{row}">
          <span>{{ row.includeModuleNames }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建人账号" align="center">
        <template slot-scope="{row}">
          <span>{{ row.createrLoginName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建人姓名" align="center">
        <template slot-scope="{row}">
          <span>{{ row.createrName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建人所属机构" align="center">
        <template slot-scope="{row}">
          <span>{{ row.createrOrganization }}</span>
        </template>
      </el-table-column>
      <el-table-column label="模块ID" align="center">
        <template slot-scope="{row}">
          <span>{{ row.includeModuleIds }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" fixed="right" width="170">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-popconfirm title="删除?" style="margin-left: 10px" @onConfirm="handleDelete(row,$index)">
            <el-button
              slot="reference"
              type="danger"
              size="mini"
            >
              删除
            </el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page-sizes="[20]" :page.sync="listQuery.currentPage" :limit.sync="listQuery.limit" @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :width="'500px'" :close-on-click-modal="false" :close-on-press-escape="false">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-width="120px" style="margin-right:20px">
        <el-form-item label="模板名称" prop="templateName">
          <el-input v-model="temp.templateName" :disabled="dialogStatus==='create'?false:true" />
        </el-form-item>
        <el-form-item label="包括模块" prop="includeModuleNames">
          <el-select v-model="temp.includeModuleNames" multiple @change="onModuleChange">
            <el-option v-for="item in moduleOptions" :key="item.moduleName" :label="item.moduleName" :value="item.moduleName" />
          </el-select>
        </el-form-item>
        <el-form-item label="模块ID">
          <el-input v-model="temp.includeModuleIds" :disabled="true" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          关闭
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          提交
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { fetchList, createArticle, updateArticle, deleteArticle } from '@/api/temp'
import { fetchList as fetchModuleList } from '@/api/task'
import waves from '@/directive/waves'
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination'
import { mapGetters } from 'vuex'

const ywTypes = [
  { key: '采集', display_name: '采集' },
  { key: '核查', display_name: '核查' },
]
const sbTypes = [
  { key: '文本', display_name: '文本' },
  { key: '图片', display_name: '图片' },
  { key: '文本与图片', display_name: '文本与图片' },
]

export default {
  name: 'Polling',
  components: { Pagination },
  directives: { waves },
  filters: {},
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        currentPage: 1,
      },
      ywTypes,
      sbTypes,
      temp: {},
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '添加'
      },
      moduleOptions: [],
      rules: {
        templateName: [{ required: true, message: '必填项', trigger: 'change' }],
        includeModuleNames: [{ required: true, message: '必填项', trigger: 'change' }],
      },
    }
  },
  computed: {
    ...mapGetters([
      'addressOptions',
      'info'
    ])
  },
  created() {
    this.getList()
    fetchModuleList({ pageSize: 999 }).then((res) => {
      this.moduleOptions = res.data.records
    })
  },
  methods: {
    getList() {
      this.listLoading = true
      fetchList(this.listQuery).then(response => {
        this.list = response.data.records
        this.total = response.data.total
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {}
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          createArticle({ ...this.temp,
            includeModuleIds: this.temp.includeModuleIds.toString(),
            includeModuleNames: this.temp.includeModuleNames.toString(),
            createrLoginName: this.info.LoginName,
            createrName: this.info.Name,
            createrOrganization: this.transSSQ() }).then(() => {
            this.dialogFormVisible = false
            this.getList()
            this.notifyMessage('创建成功')
          })
        }
      })
    },
    transSSQ() {
      const { Province, City, Area } = this.info
      let address = ''
      if (Province) {
        address = Province + '-'
      }
      if (City) {
        address = address + City + '-'
      }
      if (Area) {
        address = address + Area
      }
      return address
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row)
      this.temp.includeModuleNames = this.temp.includeModuleNames?.split(',')
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          updateArticle({ ...tempData, includeModuleNames: tempData.includeModuleNames.toString() }).then(() => {
            this.dialogFormVisible = false
            this.getList()
            this.notifyMessage('保存成功')
          })
        }
      })
    },
    notifyMessage(info) {
      this.$notify({
        title: info,
        type: 'success',
        duration: 2000
      })
    },
    handleDelete(row, index) {
      deleteArticle({ templateName: row.templateName }).then(() => {
        this.getList()
        this.notifyMessage('删除成功')
      })
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    },
    onAddress(val) {
      if (!val) { return }
      this.temp.province = val[0] || ''
      this.temp.city = val[1] || ''
      this.temp.area = val[2] || ''
    },
    onModuleChange(data) {
      const ids = data.map((item) => {
        const find = this.moduleOptions.find((op) => op.moduleName === item)
        return find?.id
      })
      this.temp.includeModuleIds = ids.toString()
    }
  }
}
</script>
